package bluejack.game.gal.diaplay;
import nme.display.Bitmap;
import nme.display.BitmapData;
import nme.display.Loader;
import nme.display.Sprite;
import nme.events.Event;
import nme.net.URLRequest;

/**
 * ...
 * @author BlueJack
 */

class Image extends Sprite
{
	public var autoCenterX:Bool;
	public var autoCenterY:Bool;
	
	private static var lib:Hash<BitmapData> = new Hash();
	private var loader:Loader;
	private var url:String;
	private var bitmap:Bitmap;

	public function new(path:String = null) {
		super();
		bitmap = new Bitmap();
		addChild(bitmap);
		autoCenterX = false;
		autoCenterY = false;
		if (path != null) load(path);
	}
	
	public function load(path:String):Void {
		url = path;
		if (lib.get(url) == null) {
			loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaded);
			loader.load(new URLRequest(url));
		}else {
			bitmap.bitmapData = lib.get(url);
			if (autoCenterX) centerX();
		if (autoCenterY) centerY();
		}
	}
	
	private function onLoaded(e:Event):Void {
		var bd:BitmapData = cast(loader.content, Bitmap).bitmapData;
		lib.set(url, bd);
		bitmap.bitmapData = bd.clone();
		if (autoCenterX) centerX();
		if (autoCenterY) centerY();
	}
	
	public function centerX():Void {
		bitmap.x = -bitmap.width / 2;
	}
	
	public function centerY():Void {
		bitmap.y = -bitmap.height / 2;
	}
}